<template>
  <div class="main">
    <div style="padding: 0 30px 30px 30px; margin: 10px; background-color: #fff">
      <a-form layout="inline" :model="form" ref="formRef" style="margin-bottom: 10px" :rules="rules">
        <a-form-item has-feedback name="inputValue">
          <span style="margin-right: 10px">退火窑:</span>
          <a-input style="width: 200px" v-model:value="form.inputValue" placeholder="请输入" @input="debounceSearch"
        /></a-form-item>
        <a-form-item v-if="form.inputValue" name="name">
          <span style="margin-right: 10px">产品名称:</span>
          <a-select style="width: 200px" v-model:value="form.name" placeholder="请选择" @change="queryTimeListByName(form.name)">
            <a-select-option v-for="(item, index) in nameList" :key="index" :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="form.name" name="datetime">
          <span style="margin-right: 10px">时间段:</span>
          <a-select
            style="width: 300px"
            v-model:value="form.datetime"
            placeholder="请选择"
            allowClear
            :disabled="timeDisable1"
            @change="datetimeChange"
          >
            <a-select-option v-for="(item, index) in timeList" :key="index" :value="index">{{ item.starTime }}-{{ item.endTime }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="form.name" name="datetime">
          <span style="margin-right: 10px">自定义时间段:</span>
          <a-range-picker
            v-model:value="form.rangeTime"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            show-time
            @change="handleTimeChange"
            allowClear
            :disabled="timeDisable2"
          />
        </a-form-item>
        <a-form-item style="margin-left: 20px">
          <a-button type="primary" @click="save" class="mr-2"> 查 询 </a-button>
          <a-button @click="reset" class="mr-2"> 重 置 </a-button>
        </a-form-item>
      </a-form>

      <table v-if="eqData.times.length > 0" class="myTable" width="100%" border="0" cellpadding="0" cellspacing="0" style="height: 100%">
        <colgroup> </colgroup>
        <thead>
          <tr>
            <th style="width: 180px"></th>
            <th style="width: 180px" v-for="(item, index) in eqData.times" :key="index">{{ item }}</th>
            <th style="width: 180px">合计</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in eqData.data" :key="index" class="dtr">
            <td v-for="(item1, index1) in item" :key="index1" :style="index1 == 0 ? 'width:180px;' : ''">{{ item1 }}</td>
            <td style="width: 180px">{{ getTotalRow(item) }}</td>
          </tr>
          <tr style="background-color: #fafafa">
            <td style="width: 180px">合计</td>
            <td style="width: 180px" v-for="(item, index) in TotalRow" :key="index">{{ item }}</td>
          </tr>
        </tbody>
      </table>
      <a-pagination
        v-if="total"
        style="margin-top: 20px; text-align: right"
        v-model:current="current"
        :total="total"
        show-less-items
        @change="pageChange"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { queryDateTime, queryName, queryEqReport } from './chart.api';
  import { Pagination } from 'ant-design-vue';
  let eqData = reactive({ times: [], data: [] });
  let nameList = reactive([]);
  let eqResult = reactive([]);
  let timeList = ref([]);
  let TotalRow = ref([]);
  let timeDisable1 = ref(false);
  let timeDisable2 = ref(false);
  let current = ref(1);
  let total = ref(0);
  const APagination = Pagination;

  onMounted(() => {});
  //选择时间事件
  const datetimeChange = (time) => {
    form.rangeTime = [];
    timeDisable2.value = typeof time === 'undefined' ? false : true;
  };
  // 日期控件change事件
  const handleTimeChange = () => {
    form.datetime = '';
    timeDisable1.value = form.rangeTime ? true : false;
  };
  // 计算合计行
  const getTotalRow = (rowData) => {
    let total = 0;
    rowData.forEach((row) => {
      if (Number(row)) total += Number(row);
    });
    return total;
  };

  //根据产品名称查询时间列表
  const queryTimeListByName = (productSpecsName) => {
    timeList.value = [];
    form.datetime = '';

    queryDateTime({ productSpecsName, productFloor: form.inputValue }).then((res) => {
      timeList.value = res;
    });
  };
  //输入框input事件
  const debounceSearch = () => {
    if (form.inputValue == '') {
      eqData.times = [];
      eqData.data = [];
      return;
    }
    queryName({ productFloor: form.inputValue }).then((res) => {
      nameList = res;
      form.name = res[0];
      queryTimeListByName(form.name);
    });
  };

  const form = reactive({
    name: '',
    inputValue: '',
    datetime: '',
    rangeTime: [],
  });
  const formRef = ref(null);
  const validateInput = (_rule, value) => {
    if (value === '') return Promise.reject('请输入!');
    var reg1 = /\d+-\d+/;
    if (!reg1.test(value)) return Promise.reject('请输入1-1此类格式!');
    return Promise.resolve();
  };
  const rules = {
    inputValue: [{ required: true, validator: validateInput, trigger: 'change' }],
    name: [{ required: true, message: '请选择产品', trigger: 'change' }],
    // datetime: [{ required: true, message: '请选择时间', trigger: 'change' }],
  };

  // 查询
  async function save() {
    try {
      const valid = await formRef.value.validate();
      let starTime = '';
      let endTime = '';
      //用自定义时间
      if (form.rangeTime.length > 0) {
        starTime = form.rangeTime[0];
        endTime = form.rangeTime[1];
      } else {
        starTime = timeList.value[form.datetime].starTime;
        endTime = timeList.value[form.datetime].endTime;
      }
      eqResult = await queryEqReport({
        starTime,
        endTime,
        productFloor: form.inputValue,
      });
      //分页设置
      total.value = eqResult.length;
      current.value = 1;

      eqResult = eqResult.reverse();
      let pageData = paginat(eqResult);

      let eqDataResult = clearData(pageData);
      eqData.times = eqDataResult?.times2 || [];
      eqData.data = eqDataResult?.data || [];
      TotalRow = getTotalCol(eqData.data);
    } catch (err) {
      console.log('err', err);
    }
  }
  // 页面切换事件
  const pageChange = (current, size) => {
    let pageData = paginat(eqResult, size, current);

    let eqDataResult = clearData(pageData);
    eqData.times = eqDataResult?.times2 || [];
    eqData.data = eqDataResult?.data || [];
    TotalRow = getTotalCol(eqData.data);
  };
  //数据前端分页
  const paginat = (data, pageSize = 10, currentPage = 1) => {
    // 确保页码是正整数
    currentPage = Math.max(1, Math.floor(currentPage));

    // 计算起始索引
    const startIndex = (currentPage - 1) * pageSize;

    // 确保不会超出数据范围
    const endIndex = Math.min(startIndex + pageSize, data.length);

    // 截取并返回指定范围的数据
    return data.slice(startIndex, endIndex);
  };

  const getTotalCol = (data) => {
    // 初始化一个数组来保存每列的合计值
    let totals = Array(data[0].length).fill(0);
    console.log('total1', totals);
    // 遍历二维数组
    for (let i = 0; i < data.length; i++) {
      // 遍历当前行的每一列
      for (let j = 1; j < data[i].length; j++) {
        // 从第二列开始，因为第一列是文字
        // 将当前数字转换为整数（或浮点数）并加到合计值上
        totals[j] += parseInt(data[i][j], 10); // 假设数字都是整数
      }
    }

    totals.push(totals.reduce((accumulator, currentValue) => accumulator + currentValue, 0));
    totals.shift();
    // 在数据数组的末尾添加合计值
    return totals;
  };
  // 重置
  function reset(e) {
    form.inputValue = '';
    form.datetime = '';
    timeList.value = [];
    eqData.times = [];
    eqData.data = [];
    TotalRow = [];
    timeDisable1 = false;
    timeDisable2 = false;
    form.rangeTime = [];
    formRef.value.resetFields();
  }
  function clearData(rawData) {
    // 首先，我们将原始数据按照时间进行分组
    if (!rawData || rawData.includes(null)) return;
    // rawData = rawData.reverse();
    const groupedByTime = rawData.reduce((acc, group) => {
      group.forEach((item) => {
        const time = item.time.split(':')[0] + ':' + item.time.split(':')[1];
        if (!acc[time]) {
          acc[time] = {};
        }
        // 使用 tagName 作为键，pvValue 作为值
        acc[time][item.tagName] = item.pvValue;
      });
      return acc;
    }, {});
    console.log('groupedByTime', groupedByTime);

    // 接下来，我们提取时间和数据，并转换为所需的格式
    const times = Object.keys(groupedByTime).map((time) => time.split(':')[0] + ':' + time.split(':')[1]); // 只取时和分
    console.log(times);
    const names = ['烂瓶类', '调试问题类', '玻璃液问题类', '规格尺寸类', '变形类', '其他类'];
    const data = Object.keys(groupedByTime[times[0]]).map((tagName, i) => {
      // 初始化数组以存储每个 tagName 在不同时间点的 pvValue
      return [names[i], ...times.map((t) => (groupedByTime[t] ? groupedByTime[t][tagName] || 0 : 0))];
    });

    let times2 = times.map((v) => formatDate(v));
    return {
      times2,
      data,
    };
  }

  function formatDate(dateStr) {
    const date = new Date(dateStr);
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加1并补零
    const day = date.getDate().toString().padStart(2, '0'); // 补零
    const HH = date.getHours().toString().padStart(2, '0');
    return `${month}-${day} ${HH}`;
  }
</script>

<style lang="less" scoped>
  .main {
    min-height: 100%;
  }

  .myTable {
    width: 100%;
    font-size: 14px;
    .dtr {
      &:hover {
        background: #fafafa;
      }
    }
    th {
      background: #fafafa;
      padding: 12px 8px;
      border: 1px solid #f0f0f0;
      font-weight: 500;
      border-inline-end: 1px solid #f0f0f0;
    }
    td {
      border: 1px solid #e5e7eb;
      padding: 12px 8px;
      text-align: center; /* 文字水平居中 */
      vertical-align: middle; /* 文字垂直居中 */
      border-inline-end: 1px solid #f0f0f0;
    }
  }

  :deep(.ant-table-thead > tr > th) {
    background-color: #0b1628; /* 设置表头背景色 */
    color: #3fa6ff !important;
  }

  .ant-form-item {
    margin-top: 20px;
  }
</style>
